#include "motor.h"
#include "global.h"
#include "main.h"

const unsigned char STEP_TAB[2][6]={{4,0,5,2,3,1},{1,3,2,5,0,4}};

//steP,为当前步，PWM_ON_flag=1时打开PWM输出
void Commutation(unsigned int step,unsigned int PWM_ON_flag)
{	 	 
	if(PWM_ON_flag==0||MOTORSTATE==STATEERROR||MOTORSTATE==STATEERROROVER)
               { 
								 	CW_ATIM->CCR1=0;CW_ATIM->CCR2=0;CW_ATIM->CCR3=0;	
									PWM_AL_OFF;	PWM_BL_OFF;	PWM_CL_OFF;
								  CW_ATIM->CCR4=PWM_PERIOD-800;								 
									return;
							 }	 
	
  if(step==0||step==5){	PWM_AL_OFF;	PWM_CL_OFF;}//AB
  else if(step==1||step==2){	PWM_AL_OFF;	PWM_BL_OFF;	}//AC
	else if(step==3||step==4){	PWM_BL_OFF;	PWM_CL_OFF;	}//BA
	
	if(step==0||step==1){	 CW_ATIM->CCR2=0;CW_ATIM->CCR3=0;CW_ATIM->CCR1=OutPwmValue;	}
	if(step==2||step==3){	 CW_ATIM->CCR1=0;CW_ATIM->CCR3=0;CW_ATIM->CCR2=OutPwmValue;	}
	if(step==4||step==5){	 CW_ATIM->CCR1=0;CW_ATIM->CCR2=0;CW_ATIM->CCR3=OutPwmValue;	}
	
	
	if(step==0||step==5){PWM_BL_ON; }//AB
  else if(step==1||step==2){PWM_CL_ON; }// AC
	else if(step==3||step==4){PWM_AL_ON; }//BA

	  STEP_last=step;
		CW_ATIM->CCR4=PWM_PERIOD>>1;//  
			
		HALLcount++;HALLcount1++;	  	
bHallStartStep1=step;	
}

void UPPWM(void)
{	
	__disable_irq(); 
	if(STEP_last==0||STEP_last==1){	 CW_ATIM->CCR2=0;CW_ATIM->CCR3=0; CW_ATIM->CCR1=OutPwmValue;	}
	if(STEP_last==2||STEP_last==3){	 CW_ATIM->CCR1=0;CW_ATIM->CCR3=0;CW_ATIM->CCR2=OutPwmValue;	}
	if(STEP_last==4||STEP_last==5){	 CW_ATIM->CCR1=0;CW_ATIM->CCR2=0;CW_ATIM->CCR3=OutPwmValue;	}
		CW_ATIM->CCR4=PWM_PERIOD>>1;//  
	__enable_irq();
}
 
 void GPIOA_IRQHandler(void)
{
	unsigned char x;
	
   GPIOA_INTFLAG_CLR(bv0|bv1|bv2);
	 x=HALL_Check();	
    if(x==0||x==7){return;} 		
	  
		Cur_step=STEP_TAB[Dir][x-1];	   
		if(Motor_Start_F==1&&ErrorCode==0)
 		Commutation(Cur_step,Motor_Start_F);  
		if(x==0||x==2||x==4)PA12_TOG(); //PA0反转，用于速度FG输出
}

unsigned char  HALL_Check(void)
{
	 static unsigned char hallerrnum=0;
	 unsigned char x=0;
	 
	 if(GPIO_ReadPin(CW_GPIOA,GPIO_PIN_0)==GPIO_Pin_SET)x=1;
	 if(GPIO_ReadPin(CW_GPIOA,GPIO_PIN_1)==GPIO_Pin_SET)x|=0x2;
	 if(GPIO_ReadPin(CW_GPIOA,GPIO_PIN_2)==GPIO_Pin_SET)x|=0x4;//000-0;001-1;010-2;011-3;100-4;101-5;110-6;111-7;
	 if(x==0||x==7)
	   {hallerrnum++;if(hallerrnum>=10){hallerrnum=10;ErrorCode=2;}}
   else hallerrnum=0;
	 return x;
}

void HALL_MOTOR_START(void)
{ 	
	unsigned char x=0; 	
		 
			if(MOTORSTATE==STATEERROR)return;
			 x=HALL_Check();	 
		 if(x==0||x==7){return;}	 
		 Cur_step=STEP_TAB[Dir][x-1];
		 RealS1=0; 
		 Motor_Start_F=1;
		 Commutation(Cur_step,Motor_Start_F);  
}

void MOTOR_STOP0(void)
{
	 Motor_Start_F=0; 
	 Commutation(0,0);
}


